#include "iic.h"
#include <intrins.h>

void delay_us(unsigned int us) 
{
		while(us--);// _nop_();
}

void iic_init() 
{
	SCL = 1;
	delay_us(1);
	SDA = 1;
	delay_us(1);
}

void iic_start() 
{
	
	SDA = 1;
	delay_us(1);
	SCL = 1;
	delay_us(1);
	SDA = 0;
	delay_us(1);
	SCL = 0;
	//delay_us(1);
}

void iic_stop() 
{
	SDA = 0;
	delay_us(1);
	SCL = 1;
	delay_us(1);
	SDA = 1;
	delay_us(1);
}

//a=0 ack  a=1 nack
void iic_ack(unsigned char a) 
{
	SDA = a;
	SCL = 0;
	delay_us(1);
	SCL = 1;
	delay_us(1);
	SCL = 0;
	delay_us(1);
}

//call iic_start() before call this function 
char iic_write_byte(unsigned char byte) 
{
	char i = 0;
	char ack = 0;
	SCL = 0;
	for(  ;i<8 ;++i)
	{
		if(byte & 0x80) {
			SDA = 1;
		} else {
			SDA = 0;
		}
		byte <<= 1;
		
		delay_us(1);
		SCL = 1;
		delay_us(1);
		SCL = 0;
		delay_us(1);
		
	}
	SDA = 1;
	//delay_us(1);
	SCL = 1;
	delay_us(1);
	ack = SDA;
	SCL = 0;
	delay_us(1);
	return ack;
}


unsigned char iic_read_byte(char ack) 
{
	char i = 0;
	unsigned char result = 0;
	SDA = 1;
	SCL = 0;
	for(  ;i<8 ;++i)
	{
		delay_us(1);
		SCL = 1;
		delay_us(1);
		result <<= 1;
		if(SDA == 1) result |= 0x01;
		SCL = 0;
		delay_us(1);
	}
	iic_ack(ack);
	return result;
}

